package com.dragonlance.thread;

import java.nio.charset.CharacterCodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.mina.core.session.IoSession;

import com.dragonlance.DLClient;
import com.dragonlance.DLServer;
import com.dragonlance.beans.User;
import com.dragonlance.net.PackageIn;

public class LoginThread implements Runnable {
	
	private String username;
	private String key;
	private IoSession session;
	private PackageIn pkg;
	public LoginThread(PackageIn pkg, IoSession session) {
		this.pkg = pkg;
		this.session = session;
	}
	@Override
	public void run(){
		try {
			username = pkg.readUtf();
			key = pkg.readUtf();
			User user = User.findByUserName(username);
			if(user != null){
				Date d = new Date(Calendar.getInstance().getTimeInMillis());
				SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
				String loginTime = formatter.format(d);
				user.setLoginTime(loginTime);
				DLClient client = new DLClient(session, user);
				DLServer.getInstance().getClientMgr().add(client);
				client.out.sendLogin(user);
			}else
			{
				this.session.close(true);
			}
		} catch (CharacterCodingException e){
			e.printStackTrace();
			session.close(true);
		}
	}
}
